package com.gaoda.booksystem.web.sys;

import com.gaoda.booksystem.entity.User;
import com.gaoda.booksystem.sysService.SysAdminService;
import com.gaoda.booksystem.sysService.SysUserService;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class AdminManage {

    //分页
    private static final long serialVersionUID = 1L;
    private static final int PAGE_COUNT = 3;//每页显示记录数


    @Autowired
    SysAdminService sysAdminService;

    //模糊查询显示管理员列表 + 分页
    @RequestMapping("/adminList")
    public String queryUserList(String name, String userSex, String userDep, String userState, Model model, HttpServletRequest request){
        //默认当前页
        int currentPage = 1;
        String page = request.getParameter("page");
        if(page != null) {
            currentPage = Integer.valueOf(page);
        }
        List<User> list = sysAdminService.queryAdmin(name, userSex, userDep, userState, currentPage, PAGE_COUNT);
        int totalPage = sysAdminService.getTotalPage(PAGE_COUNT, name, userSex, userDep, userState);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentPage", currentPage);
        model.addAttribute("list",list);
        model.addAttribute("name", name);
        model.addAttribute("userSex", userSex);
        model.addAttribute("userDep", userDep);

        return "sys/adminManage";
    }

    //逻辑删除管理员
    @RequestMapping("/deleteAdmin")
    @ResponseBody   //声明返回的数据为json格式
    public String deleteUser(int id){
        try{
            System.out.println("delete" + id);
            sysAdminService.deleteAdminById(id);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "success";
    }

    //修改封停管理员信息
    @RequestMapping("/updateAdmin")
    public String updateUser(Model model,int id){
        User user = sysAdminService.findAdminById(id);
        sysAdminService.updateAdmin(user);
        model.addAttribute("user",user);
        return "redirect:/adminList";
    }

    //修改未封停管理员信息
    @RequestMapping("/modifyAdmin")
    public String modifyUser(Model model,int id){
        User user = sysAdminService.findAdminById(id);
        sysAdminService.modifyAdmin(user);
        model.addAttribute("user",user);
        return "redirect:/adminList";
    }

    //显示管理员详细信息
    @RequestMapping("/showAdminDetail")
    public String userDetail(Model model,int id){
        User user = sysAdminService.findAdminById(id);
        model.addAttribute("user",user);
        return "sys/adminDetail";
    }

    //修改管理员信息
    @RequestMapping("/updateAdminManage")
    public String updateUserManage(User user,HttpServletRequest request){
        int id = Integer.parseInt(request.getParameter("id"));
        String username = request.getParameter("username");
        String name = request.getParameter("name");
        int userSex = Integer.parseInt(request.getParameter("userSex"));
//        Date userTime = request.getParameter("userTime");

        String userTel = request.getParameter("userTel");
        String userDep = request.getParameter("userDep");
        int age = Integer.parseInt(request.getParameter("age"));
        user = new User(id,name,userSex,age,userDep,username,userTel);

        sysAdminService.updateAdminById(user);

        return "redirect:/adminList";
    }

    //跳转到添加管理员的页面
    @RequestMapping("/jumpToAddAdmin")
    public String jumpToAddAdmin(){
        return "sys/addAdmin";
    }

    //添加管理员
    @RequestMapping("/addAdmin")
    public String addAdmin(User user) {
//        System.out.println("111");
        Date date =new Date();
        user.setUserTime(date);
        BCryptPasswordEncoder encoder =new BCryptPasswordEncoder();
        user.setPassword(encoder.encode(user.getPassword().trim()));
        sysAdminService.insertAdmin(user);
//        System.out.println(user);
        return "redirect:/adminList";
    }

    //导出管理员信息
    @RequestMapping(value = "/loadSysAdmin", method = RequestMethod.GET)
    public void loadBook(HttpServletResponse response) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("用户信息表");
        //获取数据
        List<User> userList = sysAdminService.adminList();

        //设置要导出的文件的名字
        String fileName = "AdminList" + ".xls";

        //新增数据行，并且设置单元格数据
        int rowNum = 1;

        //headers表示excel表中第一行的表头
        String[] headers = {"用户名", "用户编号", "性别", "年龄", "注册时间", "电话号码", "所属部门", "用户类型"};

        //在excel表中添加表头
        HSSFRow row = sheet.createRow(0);

        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (User user : userList) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(user.getName());
            row1.createCell(1).setCellValue(user.getUsername());
            String sex=(user.getUserSex())== 1 ? "男": "女";
            row1.createCell(2).setCellValue(sex);
            row1.createCell(3).setCellValue(user.getAge());
            row1.createCell(4).setCellValue(sdf.format(user.getUserTime()));
            row1.createCell(5).setCellValue(user.getUserTel());
            String d = user.getUserDep();
            String userDep = d.equals("1") ? "总经理办公室" :
                    ((d.equals("2") ? "人力资源部" :
                            (d.equals("3") ? "财务部" :
                                    ((d.equals("4") ? "生产技术部" :
                                            ((d.equals("5") ? "计划营销部" : (
                                                    (d.equals("6") ? "安全监察部" : "后勤部")))))))));
            row1.createCell(6).setCellValue(userDep);
            row1.createCell(7).setCellValue(user.getUserType());
            rowNum++;
        }

        //根据内容自动调整列宽
        HSSFSheet hssfSheet = workbook.getSheetAt(0);
        hssfSheet.autoSizeColumn((short)0);
        hssfSheet.autoSizeColumn((short)1);
        hssfSheet.autoSizeColumn((short)2);
        hssfSheet.autoSizeColumn((short)3);
        hssfSheet.autoSizeColumn((short)4);
        hssfSheet.autoSizeColumn((short)6);
        hssfSheet.autoSizeColumn((short)7);

        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition","attachment;filename="+ fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

}
